import Immutable from 'immutable';
import moment from 'moment';
// import { routerRedux } from 'dva/router';
import {
  queryPayCouponList,
  calCoupon,
  queryCouponList,
  queryGiftStatus,
  getGiftPackage,
} from '../services/coupon';
// import { pay as wechatPay } from '../utils/wechat';
import toast from '../utils/toast';
import {
  COUPON_GIFT_SH,
  COUPON_GIFT_SHELL,
  COUPON_GIFT_MORE,
} from '../constants/setting';

const CouponRecord = Immutable.Record({
  id: null,
  canPresent: false, // 是否可以赠送
  desc: null, // 不可用时的描述
  expireTime: null,
  receiveTime: null,
  amount: null, // 满减
  amountYuan: null,
  giftAmount: null, // 面额
  giftAmountYuan: null,
  selected: false, // 是否选中
  disabled: false, // 是否不可选
  couponType: null, // 1 满减 2折扣 3 代金券 4 兑换券 5 天猫券
  oilCompanyId: [],
  outCouponNo: null,
  oilCompanyName: [],
  couponStatus: 2, // 1 待领取 2 已领取 3 已使用 4 已失效 5 赠送待领取 6 赠送已领取 7 待激活
  content: '',
  enable: null,
  verifyTime: null, // 使用时间
}, 'Coupon');

export class Coupon extends CouponRecord {
  getTitle() {
    let title;
    switch (this.get('couponType')) {
      case 5:
        title = '电子加油券';
        break;
      case 1:
        title = `加油满${this.get('amountYuan')}元可使用`;
        break;
      case 7:
        title = '现金券-满200元可用';
        break;
      default:
        title = '优惠券';
        break;
    }
    return title;
  }

  isActive() {
    const active = [2, 6].includes(this.get('couponStatus')) && this.get('enable') !== 1;
    console.log('-----------!!!!h', active);
    return active;
  }

  getBadge() {
    let badge;
    switch (this.get('couponType')) {
      case 5:
        badge = '电子券';
        break;
      case 1:
        badge = '满减券';
        break;
      case 7:
        badge = '现金券';
        break;
      default:
        badge = '优惠券';
        break;
    }
    return badge;
  }

  getText() {
    let text;
    switch (this.get('couponType')) {
      case 5:
        text = `${this.get('receiveTime')}-${this.get('expireTime')}`;
        break;
      case 7:
        text = this.get('couponStatus') === 7 ? '续保后可激活' : `有效期至${this.get('expireTime')}`;
        break;
      default:
        text = `有效期至${this.get('expireTime')}`;
        break;
    }
    return text;
  }

  getUseTime() {
    return `使用时间: ${this.get('verifyTime')}`;
  }

  isTmall() {
    return this.get('couponType') === 5;
  }
}

// const fakeCoupon = new Coupon({
//   id: '123',
//   giftAmount: '100',
//   selected: true,
// });

export default {
  namespace: 'coupon',
  state: Immutable.fromJS({
    payCouponList: [],
    maxSelect: 0,
    userSelected: false,
    couponList: {
      useable: {
        page: 1,
        hasMore: true,
        list: [],
      },
      unuseable: {
        page: 1,
        hasMore: true,
        list: [],
      },
    },
    dialog: {
      needCarNo: false,
      show: false,
      type: 'sh',
    },
    moreCoupon: {
      num: 0,
    },
  }),

  effects: {
    *fetchMoreCouponInfo(_, { call, put }) {
      const res = yield call(queryGiftStatus, { markId: COUPON_GIFT_MORE });
      if (res.success) {
        yield put({
          type: 'updateMoreCouponInfo',
          payload: res.data,
        });
      }
    },
    *getMoreCoupon(_, { call, put }) {
      const res = yield call(getGiftPackage, { markId: COUPON_GIFT_MORE });
      if (res.success) {
        toast('领券成功');
        yield put({
          type: 'moreCouponSuccess',
        });
      }
    },
    *fetchDialogStatus(_, { put, take, select }) {
      yield put.resolve({
        type: 'fetchShDialog',
      });
      const show = yield select(state => state.coupon.getIn(['dialog', 'show']));
      if (show) {
        yield take('closeDialog');
      }
      yield put({
        type: 'fetchShellDialog',
      });
    },
    *fetchShDialog(_, { call, put }) {
      const res = yield call(queryGiftStatus, { markId: COUPON_GIFT_SH });
      if (res.success) {
        yield put({
          type: 'updateDialog',
          payload: { ...res.data, type: 'sh' },
        });
      }
    },
    *fetchShellDialog(_, { call, put }) {
      const res = yield call(queryGiftStatus, { markId: COUPON_GIFT_SHELL });
      if (res.success) {
        yield put({
          type: 'updateDialog',
          payload: { ...res.data, type: 'shell' },
        });
      }
    },
    *getGiftPackage({ payload }, { call, put }) {
      const res = yield call(getGiftPackage, payload);
      if (res.success) {
        toast('领券成功');
        yield put({
          type: 'closeDialog',
          payload: { needCarNo: false },
        });
      }
    },
    *fetchCouponList({ payload }, { call, put }) {
      const res = yield call(queryCouponList, payload);
      if (res.success) {
        yield put({
          type: 'updateCouponList',
          payload: { type: payload.status === 1 ? 'unuseable' : 'useable', ...res.data },
        });
      }
    },
    *fetchAndCalPayCoupon({ payload }, { put }) {
      const { listParams, calParams } = payload;
      yield put.resolve({
        type: 'fetchPayCouponList',
        payload: listParams,
      });
      yield put({
        type: 'calCoupon',
        payload: calParams,
      });
    },
    *fetchAndCalPayCouponWithoutSelect({ payload }, { put }) {
      const { listParams, calParams } = payload;
      yield put.resolve({
        type: 'fetchPayCouponList',
        payload: listParams,
      });
      yield put.resolve({
        type: 'calCoupon',
        payload: calParams,
      });
      yield put({
        type: 'disSelectAllCoupon',
      });
    },
    *fetchPayCouponList({ payload }, { call, put }) {
      const res = yield call(queryPayCouponList, payload);
      if (res.success) {
        yield put({
          type: 'updatePayCouponList',
          payload: res.data,
        });
      }
    },
    *calCoupon({ payload }, { call, put }) {
      const res = yield call(calCoupon, payload);
      if (res.success && res.data) {
        yield put({
          type: 'updateCouponStatus',
          payload: res.data,
        });
      }
    },
  },

  reducers: {
    disSelectAllCoupon(state) {
      return state.set('payCouponList', state.get('payCouponList').map(coupon => coupon.set('selected', false)));
    },
    updateMoreCouponInfo(state, { payload }) {
      return state.setIn(['moreCoupon', 'num'], Math.max(0, payload.planNum || 0));
    },
    moreCouponSuccess(state) {
      const num = state.getIn(['moreCoupon', 'num']);
      return state.setIn(['moreCoupon', 'num'], Math.max(0, num - 3));
    },
    couponUsed(state, { payload }) {
      let list = state.getIn(['couponList', 'useable', 'list']);
      list = list.map((item) => {
        if (item.get('id') === payload.id) {
          return item.set('couponStatus', 3).set('verifyTime', moment().format('YYYY-MM-DD')).set('desc', '已使用');
        } else {
          return item;
        }
      });
      return state.setIn(['couponList', 'useable', 'list'], list);
    },
    closeDialog(state, { payload }) {
      let newState = state.setIn(['dialog', 'show'], false);
      if (payload && payload.needCarNo === false) {
        newState = newState.setIn(['dialog', 'needCarNo'], false);
      }
      return newState;
    },
    updateDialog(state, { payload }) {
      return state.mergeIn(['dialog'], {
        show: payload.canSend === 1,
        needCarNo: payload.hasCardNo === 0,
        type: payload.type,
      });
    },
    updateCouponList(state, { payload }) {
      const { type } = payload;
      let list = state.getIn(['couponList', type, 'list']);
      if (payload.targetPage === 1) {
        list = list.clear();
      }
      payload.resultList.forEach((item) => {
        list = list.push(new Coupon({
          id: item.couponDetailId,
          ...item,
          desc: item.couponDesc,
          oilCompanyId: Immutable.fromJS((item.oilCompanyId || '').split(',')),
          oilCompanyName: Immutable.fromJS((item.oilCompanyName || '').split(',')),
        }));
      });
      return state.mergeIn(['couponList', type], {
        list,
        page: payload.targetPage,
        hasMore: payload.targetPage < payload.pageCount,
      });
    },
    sortCouponList(state) {
      let payCouponList = state.get('payCouponList');
      payCouponList = payCouponList.sort((pre, next) => {
        if (pre.get('selected') !== next.get('selected')) {
          return pre.get('selected') ? -1 : 1;
        } else if (pre.get('disabled') !== next.get('disabled')) {
          return pre.get('disabled') ? 1 : -1;
        } else {
          return 0;
        }
      });
      return state.set('payCouponList', payCouponList);
    },
    updateCouponStatus(state, { payload }) {
      let payCouponList = state.get('payCouponList');
      const { selectIds = [], disableIds = [] } = payload;
      payCouponList = payCouponList.map((coupon) => {
        const id = coupon.get('id');
        return coupon.set('selected', selectIds.includes(id)).set('disabled', disableIds.includes(id));
      });
      return state.merge({
        payCouponList,
        maxSelect: payload.remainCounts,
      });
    },
    updatePayCouponList(state, { payload }) {
      const couponList = Immutable.fromJS(payload.map((item) => {
        return new Coupon({
          id: item.couponDetailId,
          ...item,
        });
      }));
      return state.merge({
        payCouponList: couponList,
        maxSelect: couponList.size,
      });
    },
    selectRefuelCoupon(state, { payload }) {
      const { selectCoupon, number } = payload;
      if (selectCoupon.get('disabled') && !selectCoupon.get('selected')) {
        toast('该优惠券不满足此次使用条件');
        return state;
      }
      const maxSelect = state.get('maxSelect');
      let list = state.get('payCouponList');
      const selectList = list.filter(coupon => coupon.get('selected'));
      if (selectCoupon.isTmall()) {
        console.log('tmall----');
      } else {
        const totalAmount = selectList.reduce((total, coupon) => total + coupon.get('amount'), 0);
        console.log('total totalAmount', totalAmount, selectCoupon.get('amount'), number * 100);
        if (!selectCoupon.get('selected') && totalAmount + selectCoupon.get('amount') > number * 100) {
          toast('满减金额不能超过加油金额');
          return state;
        }
      }

      const selectCount = selectList.size;
      list = list.map((coupon) => {
        if (coupon === selectCoupon) {
          if (selectCount >= maxSelect && !coupon.get('selected')) {
            toast(`最多可使用${maxSelect}张优惠券`);
            return coupon;
          } else {
            return coupon.set('selected', !coupon.get('selected'));
          }
        } else {
          return coupon;
        }
      });
      return state.merge({
        payCouponList: list,
        userSelected: true,
      });
    },
  },
};
